<{include file="v2/header.html"}>
<main class="pt-24 pb-16">
    <!-- 面包屑导航 -->
    <section class="container mx-auto px-4 mb-8">
        <div class="text-sm text-lightink">
            <a href="bookList.html" class="hover:text-cinnabar transition-colors">古籍藏本</a>
            <span class="mx-2">/</span>
            <span id="book-category">经部</span>
            <span class="mx-2">/</span>
            <span id="book-title">论语</span>
        </div>
    </section>
    
    <!-- 古籍详情 -->
    <section class="container mx-auto px-4 mb-16">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- 古籍封面 -->
            <div class="lg:col-span-1">
                <div class="bg-rice rounded-xl overflow-hidden shadow-sm p-4">
                    <img id="book-cover" src="https://picsum.photos/id/24/600/800" alt="古籍封面" class="w-full rounded-lg">
                    
                    <div class="mt-6 grid grid-cols-2 gap-4">
                        <button id="collect-btn" class="bg-cinnabar text-rice py-3 rounded-lg hover:bg-opacity-90 transition-all flex items-center justify-center">
                            <i class="fa fa-heart-o mr-2"></i> 收藏
                        </button>
                        <button id="share-btn" class="border border-ink text-ink py-3 rounded-lg hover:bg-ink hover:text-rice transition-all flex items-center justify-center">
                            <i class="fa fa-share-alt mr-2"></i> 分享
                        </button>
                    </div>
                </div>
                
                <!-- 古籍信息 -->
                <div class="bg-rice rounded-xl shadow-sm p-6 mt-6">
                    <h3 class="text-lg font-song font-bold mb-4">古籍信息</h3>
                    <ul class="space-y-3 text-sm">
                        <li class="flex justify-between">
                            <span class="text-lightink">作者</span>
                            <span id="book-author">孔子及其弟子</span>
                        </li>
                        <li class="flex justify-between">
                            <span class="text-lightink">年代</span>
                            <span id="book-period">春秋时期</span>
                        </li>
                        <li class="flex justify-between">
                            <span class="text-lightink">版本</span>
                            <span id="book-edition">明刻本</span>
                        </li>
                        <li class="flex justify-between">
                            <span class="text-lightink">分类</span>
                            <span id="book-category-detail">经部</span>
                        </li>
                        <li class="flex justify-between">
                            <span class="text-lightink">字数</span>
                            <span id="book-word-count">约15,900字</span>
                        </li>
                        <li class="flex justify-between">
                            <span class="text-lightink">浏览量</span>
                            <span id="book-views">12,543</span>
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- 古籍内容 -->
            <div class="lg:col-span-2">
                <div class="bg-rice rounded-xl shadow-sm p-6 md:p-8">
                    <h1 id="book-title-main" class="text-[clamp(1.5rem,3vw,2.5rem)] font-song font-bold mb-2">论语</h1>
                    <p class="text-lightink mb-6" id="book-meta">孔子及其弟子 · 春秋时期</p>
                    
                    <!-- 阅读工具 -->
                    <div class="border-b border-gray-200 pb-4 mb-6 flex flex-wrap gap-4 items-center">
                        <div class="flex items-center gap-2">
                            <button class="p-2 hover:bg-gray-100 rounded transition-colors" title="字体减小">
                                <i class="fa fa-font text-sm"></i>
                            </button>
                            <button class="p-2 hover:bg-gray-100 rounded transition-colors" title="字体增大">
                                <i class="fa fa-font"></i>
                            </button>
                        </div>
                        
                        <div class="flex items-center gap-2">
                            <button class="p-2 hover:bg-gray-100 rounded transition-colors" title="背景色">
                                <i class="fa fa-adjust"></i>
                            </button>
                            <button class="p-2 hover:bg-gray-100 rounded transition-colors" title="目录">
                                <i class="fa fa-list"></i>
                            </button>
                        </div>
                        
                        <div class="flex items-center gap-2 ml-auto">
                            <button class="p-2 hover:bg-gray-100 rounded transition-colors" title="上一页">
                                <i class="fa fa-angle-left"></i>
                            </button>
                            <span class="text-sm">第 <span id="current-page">1</span> 页</span>
                            <button class="p-2 hover:bg-gray-100 rounded transition-colors" title="下一页">
                                <i class="fa fa-angle-right"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- 内容区域 -->
                    <div id="book-content" class="prose prose-lg max-w-none text-ink/90 font-song">
                        
                    </div>
                    
                    <!-- 分页 -->
                    <div class="mt-10 flex justify-between items-center">
                        <button id="prev-chapter" class="text-cinnabar hover:text-cinnabar/80 transition-colors flex items-center">
                            <i class="fa fa-angle-left mr-2"></i> 上一章
                        </button>
                        <button id="next-chapter" class="text-cinnabar hover:text-cinnabar/80 transition-colors flex items-center">
                            下一章 <i class="fa fa-angle-right ml-2"></i>
                        </button>
                    </div>
                </div>
                
                <!-- 相关推荐 -->
                <div class="mt-8">
                    <h3 class="text-xl font-song font-bold mb-6">相关古籍</h3>
                    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
                        <!-- 相关古籍1 -->
                        <{foreach from=$res_guji item=val}>
                            <a href="index.php?c=main&a=gjDetails&id=<{$val.id}>" class="bg-rice rounded-lg overflow-hidden shadow-sm flex">

                                <img src="<{$val.coverUrl}>" alt="<{$val.title}>" class="w-24 h-auto object-cover">


                                <div class="p-3">
                                    <h4 class="font-song font-bold text-sm"><{$val.title}></h4>
                                    <p class="text-xs text-lightink"><{$val.author}> · <{$val.niandai}></p>
                                </div>
                            </a>
                        <{/foreach}>                        
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>

<script>
    // 获取URL中的书籍ID
    function getBookId() {
        const params = new URLSearchParams(window.location.search);
        return params.get('id');
    }
    
    // 加载书籍详情
    function loadBookDetail(bookId) {
        // 调用API获取书籍详情
        fetch(`index.php?c=main&a=getBookDetail&id=${bookId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();  // 返回Promise，等待解析完成
            })
            .then(data => {  // 这里才能获取到解析后的JSON数据
                var book = data.data.book;
                var content = data.data.content;
                var list = data.data.list;
                // 更新页面内容
                document.getElementById('book-title').textContent = book.title;
                document.getElementById('book-title-main').textContent = book.title;
                document.getElementById('book-author').textContent = book.author;
                document.getElementById('book-period').textContent = book.niandai;
                document.getElementById('book-edition').textContent = '';
                document.getElementById('book-category').textContent = book.tags;
                document.getElementById('book-category-detail').textContent = '';
                document.getElementById('book-word-count').textContent = '';
                document.getElementById('book-views').textContent = book.views;
                document.getElementById('book-meta').textContent = `${book.author} · ${book.niandai}`;
                document.getElementById('book-cover').src = book.coverUrl;
                document.getElementById('book-cover').alt = book.title;
                
                // 加载书籍内容
                loadBookContent(bookId);
            })
            .catch(error => {
                console.error('获取书籍详情失败:', error);
                alert('无法加载书籍详情，请稍后重试');
            });
    }
    
    // 加载书籍内容
    function loadBookContent(bookId, page = 1) {
        fetch(`index.php?c=main&a=getBookContent&id=${bookId}&page=${page}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                var book = data.data.book;
                var pager = data.data.pager;

                document.getElementById('book-content').innerHTML = book.content;
                document.getElementById('current-page').textContent = page;
                
                // 保存当前页码用于上下页导航
                window.currentBookPage = page;
                window.totalBookPages = pager.total_page;
            })
            .catch(error => {
                console.error('获取书籍内容失败:', error);
            });
    }
    
    // 页面加载完成后初始化
    $(document).ready(function() {
        const bookId = getBookId();
        
        if (bookId) {
            loadBookDetail(bookId);

            // 检查收藏状态
        fetch(`index.php?c=main&a=checkCollection&book_id=${bookId}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 1 && data.data.is_collected) {
                    const btn = document.getElementById('collect-btn');
                    const icon = btn.querySelector('i');
                    const text = btn.querySelector('span');
                    icon.classList.remove('fa-heart-o');
                    icon.classList.add('fa-heart');
                    text.textContent = '已收藏';
                }
            });
        } else {
            alert('未找到书籍信息');
            window.location.href = 'bookList.html';
        }
        
        // 上一页按钮
        document.getElementById('prev-chapter').addEventListener('click', function() {
            console.log('上一页按钮点击');

            if (window.currentBookPage > 1) {
                loadBookContent(bookId, window.currentBookPage - 1);
            }
        });
        
        // 下一页按钮
        document.getElementById('next-chapter').addEventListener('click', function() {
            console.log('下一页按钮点击');

            if (window.currentBookPage < window.totalBookPages) {
                loadBookContent(bookId, window.currentBookPage + 1);
            }
        });
        
        // 字体大小调整
        const fontButtons = document.querySelectorAll('.fa-font').forEach((btn, index) => {
            btn.parentElement.addEventListener('click', function() {
                const content = document.getElementById('book-content');
                const currentSize = window.getComputedStyle(content).fontSize;
                const currentSizeNum = parseFloat(currentSize);
                
                if (index === 0) {
                    // 减小字体
                    content.style.fontSize = (currentSizeNum - 2) + 'px';
                } else {
                    // 增大字体
                    content.style.fontSize = (currentSizeNum + 2) + 'px';
                }
            });
        });
        // 替换原背景色切换功能代码
        document.querySelector('.fa-adjust').parentElement.addEventListener('click', function() {
            const body = document.body;
            const contentArea = document.getElementById('book-content').parentElement;
            const bookContent = document.getElementById('book-content');
            
            // 切换深色模式类
            body.classList.toggle('dark-mode');
            
            if (body.classList.contains('dark-mode')) {
                // 深色模式样式
                contentArea.style.backgroundColor = '#333';
                contentArea.style.color = '#f0f0f0';
                bookContent.style.color = '#f0f0f0';
            } else {
                // 恢复浅色模式（使用实际颜色值）
                contentArea.style.backgroundColor = '';
                contentArea.style.color = '';
                bookContent.style.color = 'rgba(0, 0, 0, 0.9)'; // 替换为text-ink/90对应的实际颜色值
            }
        });
        // 目录功能
        document.querySelector('.fa-list').parentElement.addEventListener('click', function() {
            // 这里假设通过API获取目录数据，实际项目中替换为真实接口
            fetch(`index.php?c=main&a=getBookChapter&id=${bookId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                var chapters = data.data.list;

                // 创建目录弹窗
                let catalogHtml = `
                    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
                        <div class="bg-rice rounded-xl shadow-lg w-full max-w-md max-h-[80vh] overflow-y-auto">
                            <div class="p-6 border-b">
                                <h3 class="text-xl font-bold">目录</h3>
                                <button class="absolute top-4 right-4 text-lightink hover:text-ink">
                                    <i class="fa fa-times"></i>
                                </button>
                            </div>
                            <ul class="p-4">
                `;

                // 添加目录项
                var _page = 1;
                chapters.forEach(chapter => {
                    catalogHtml += `
                        <li class="py-2 border-b border-gray-100">
                            <a href="#" class="chapter-link" data-chapter="${_page}">
                                ${chapter.title}
                            </a>
                        </li>
                    `;
                    _page++;

                });

                catalogHtml += `
                            </ul>
                        </div>
                    </div>
                `;

                // 添加到页面并显示
                document.body.insertAdjacentHTML('beforeend', catalogHtml);
                
                // 目录项点击事件
                document.querySelectorAll('.chapter-link').forEach(link => {
                    link.addEventListener('click', function(e) {
                        e.preventDefault();
                        const chapterId = this.getAttribute('data-chapter');
                        // 加载对应章节内容
                        loadBookContent(bookId, chapterId);
                        // 关闭目录
                        document.querySelector('.fixed.inset-0').remove();
                    });
                });
                
                // 关闭按钮事件
                document.querySelector('.fa-times').parentElement.addEventListener('click', function() {
                    document.querySelector('.fixed.inset-0').remove();
                });

            })
            .catch(error => {
                console.error('获取书籍章节失败:', error);
            });
        });
    });
</script>


<!-- 在script区域添加功能代码 -->
<script>
// 收藏功能
document.getElementById('collect-btn').addEventListener('click', function() {
    const bookId = getBookId();
    const btn = this;
    const icon = btn.querySelector('i');
    const text = btn.querySelector('span');

    // 检查登录状态
    fetch('index.php?c=main&a=getUserInfo')
        .then(response => response.json())
        .then(data => {
            if (data.code !== 1) {
                showToast('请先登录才能收藏',true);
                return;
            }

            // 已登录，调用收藏接口
            fetch(`index.php?c=main&a=toggleCollection&book_id=${bookId}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 1) {
                    if (result.data.is_collected) {
                        // 收藏成功
                        icon.classList.remove('fa-heart-o');
                        icon.classList.add('fa-heart');
                        text.textContent = '已收藏';
                        showToast('收藏成功');
                    } else {
                        // 取消收藏成功
                        icon.classList.remove('fa-heart');
                        icon.classList.add('fa-heart-o');
                        text.textContent = '收藏';
                        showToast('已取消收藏');
                    }
                } else {
                    showToast(result.msg || '操作失败',true);

                }
            });
        });
});

// 分享功能
document.getElementById('share-btn').addEventListener('click', function() {
    const bookId = getBookId();
    const bookTitle = document.getElementById('book-title').textContent;
    const shareUrl = window.location.href;

    // 检查浏览器是否支持原生分享
    if (navigator.share) {
        navigator.share({
            title: bookTitle,
            text: `推荐你阅读《${bookTitle}》`,
            url: shareUrl
        })
        .then(() => console.log('分享成功'))
        .catch((error) => console.log('分享失败:', error));
    } else {
        // 不支持原生分享则复制链接
        navigator.clipboard.writeText(shareUrl)
            .then(() => {
                showToast('链接已复制到剪贴板，可以粘贴分享了');
            })
            .catch(err => {
                console.error('无法复制链接: ', err);
                showToast('复制失败，请手动复制链接',true);
            });
    }
});
</script>
<{include file="v2/footer.html"}>